﻿Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Drawing

Public Class ExtractorIconos

    <DllImport("Shell32.dll")> _
    Private Shared Function SHGetFileInfo(ByVal pszPath As String, ByVal dwFileAttributes As UInteger, ByRef psfi As SHFILEINFO, ByVal cbfileInfo As UInteger, ByVal uFlags As SHGFI) As Integer
    End Function

    <StructLayout(LayoutKind.Sequential)> _
    Private Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As UInteger
        <MarshalAs(UnmanagedType.LPStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.LPStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Private Enum SHGFI
        SmallIcon = &H1
        LargeIcon = &H0
        Icon = &H100
        UseFileAttributes = &H10
        'vfvg
    End Enum

    ''' <summary>
    ''' Obtiene el icono asociado a la extensión del archivo a cargar. En caso de excepción
    ''' devuelve Nothing.
    ''' </summary>
    ''' <param name="strPath">path al archivo del icono</param>
    ''' <param name="sonSmall">Si es true, devuelve el icono 16x16, sino el 32x32</param>
    Public Shared Function ObtenerIconos(ByVal strPath As String, ByVal sonSmall As Boolean) As Icon
        Dim info As New SHFILEINFO()
        Dim cbFileInfo As Integer = Marshal.SizeOf(info)
        Dim flags As SHGFI

        If sonSmall Then
            flags = SHGFI.Icon Or SHGFI.SmallIcon
        Else
            flags = SHGFI.Icon Or SHGFI.LargeIcon
        End If
        SHGetFileInfo(strPath, 256, info, CUInt(cbFileInfo), flags)
        Try
            Return Icon.FromHandle(info.hIcon)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

End Class

